package com.yitong.xjd.services;

import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yitong.base.TuiSongUtils;
import com.yitong.xjd.dao.XinJinDaiDao;
import com.yitong.xjd.domain.CustCreditRecord;
import com.yitong.xjd.domain.CustSalLoanScoreInfo;
import com.yitong.xjd.domain.RequestDataOrg;
import com.yitong.xjd.domain.RequestDataPh;
import com.yitong.xjd.domain.RequestDataXjd;
import com.yitong.xjd.domain.RequestDataZm;
import com.yitong.xjd.domain.RequestDataZx;
import com.yitong.xjd.domain.ReturnData4Org;
import com.yitong.xjd.domain.ReturnData4Ph;
import com.yitong.xjd.domain.ReturnData4Rh;
import com.yitong.xjd.domain.ReturnData4Xjd;
import com.yitong.xjd.domain.ReturnData4Zm;
import com.yitong.xjd.domain.ReturnData4Zx;
import com.yitong.xjd.domain.ZxcxData;

@Service
@Transactional(value = "secondTxManager", rollbackFor = Exception.class)
public class XinJinDaiServiceImpl implements XinJinDaiService{
	public static ObjectMapper objectMapper = new ObjectMapper();
	
	//征信查询地址
	@Value("${crm.rhzx.url}")
	public String rhzxurl;	
	
	//手机银行地址
	@Value("${crm.sjyh.url}")
	public String sjyhurl;	
	
	//芝麻积分查询地址
	@Value("${crm.zmxy.url}")
	public String zmxyurl;
	
	//是否取消征信查询（测试用）
	@Value("${crm.sjyh.xjd.isqxzx}")
	public String isqxzx;	
	
	//薪金贷最高限额
	@Value("${crm.sjyh.xjd.limited}")
	public String limited;		
	
	@Autowired
	private XinJinDaiDao custDaiKuanDao;
	
	//薪金贷额度计算
	@Override
	public ReturnData4Xjd queryXjded(RequestDataXjd o) {
		ReturnData4Xjd result=null;
		
		if(o.getCustidtno()==null||o.getCustno()==null){
			result=new ReturnData4Xjd(o.getCustno(),"0","报文缺失重要字段","0"); 
		}else{
			System.out.println("白名单查询中。。。");
			String n=custDaiKuanDao.getFromWhitList(o.getCustidtno());//查询白名单
			if(n!=null){
				System.out.println("本地征信记录查询中。。。");
				CustCreditRecord record=custDaiKuanDao.getZxjlFromLocal(o.getCustidtno().toUpperCase());//获取本地征信记录
				if(record!=null){
					System.out.println("是否逾期客户。。。");
					if(!record.getYuqiFlag().equals("1")){
						System.out.println("评分记录查询中。。。");
						CustSalLoanScoreInfo entity=custDaiKuanDao.getBeanByCustIdtNo(o.getCustidtno());
						if(entity!=null){
							copyToEntity(record,entity);
							entity.setUnitRiskRank(n);
							result = calcXjdEdu(o, entity);
						}else{
							result=new ReturnData4Xjd(o.getCustno(),"0","找不到本地客户信息","0");
						}
					}else{
						result=new ReturnData4Xjd(o.getCustno(),"5","审核未通过","0");
					}
				}else{
					if(isqxzx.equals("true")){
						System.out.println("评分记录查询中。。。..");
						CustSalLoanScoreInfo entity=custDaiKuanDao.getBeanByCustIdtNo(o.getCustidtno());
						if(entity!=null){
							entity.setUnitRiskRank(n);
							result = calcXjdEdu(o, entity);
						}else{
							result=new ReturnData4Xjd(o.getCustno(),"0","找不到本地客户信息","0");
						}
					}else{
						System.out.println("是否征信在查询中。。。。。");
						if(custDaiKuanDao.isExistInBak(o.getCustidtno(),"1")){//检查是否在征信查询中
							result= new ReturnData4Xjd(o.getCustno(),"3","征信查询中。。。","0");
						}else { 
							result=new ReturnData4Xjd(o.getCustno(),"2","暂无本地征信记录，请先查询征信接口","0"); 
						}
					}
				}
			}else{
				result=new ReturnData4Xjd(o.getCustno(),"4","该客户没有薪金贷许可权限","0");
			}
		}
		return result;
	}
	
	//计算额度
	private ReturnData4Xjd calcXjdEdu(RequestDataXjd o, CustSalLoanScoreInfo entity) {
		ReturnData4Xjd result;
		try{
			custDaiKuanDao.updateEntity(entity);
			double score=custDaiKuanDao.getScoreByEntity(entity,o.getCustno(),false);
			Double salary=Double.valueOf(entity.getCustMonthSalary());
			System.out.println("月薪:"+salary);
			double daikuane=this.getDaiKuanEDu(score,salary);
			System.out.println("贷款额度:"+daikuane);
			String str="";
			if(daikuane>Double.parseDouble(limited)){
				str=new DecimalFormat("0").format(Double.parseDouble(limited)*100);
			}else{
				str=new DecimalFormat("0").format(Math.floor(daikuane/100.0)*10000);
			}
			result=new ReturnData4Xjd(o.getCustno(),"1","计算成功!!",str,custDaiKuanDao.getNowTime("yyyy-MM-dd"));
		} catch (Exception e) {
			e.printStackTrace();
			result=new ReturnData4Xjd(o.getCustno(),"0","计算过程异常","0");
		}
		return result;
	}
	
	//将转化后的record放入entity
	private void copyToEntity(CustCreditRecord record, CustSalLoanScoreInfo entity) {
		if(record!=null&&entity!=null){
			//年龄c0(34)
			String agecode="1";
			try {
				String agestr=record.getCustAge();
				if(agestr==null||agestr.equals("")){
					agecode="1";
				}else{
					int age=Integer.parseInt(agestr);
					if(age>0&&age<=25){
						agecode="1";
					}else if(age>25&&age<30){
						agecode="2";
					}else if(age>=30&&age<49){
						agecode="3";
					}else if(age>=50&&age<=59){
						agecode="4";
					}else if(age>59){
						agecode="5";
					}else{
						agecode="1";
					}
				}
			} catch (Exception e) {
				agecode="1";
				System.out.println("年龄转化为编码失败");
			}
			entity.setCustAge(agecode);
			
			
			//婚姻c1（未婚）
			String marrcode="2";
			try {
				String marr=record.getCustMarr();
				if(marr==null||marr.equals("")){
					marrcode="2";
				}else{
					if(marr.indexOf("已婚")!=-1){
						marrcode="1";
					}else if(marr.indexOf("未婚")!=-1){
						marrcode="2";
					}else{
						marrcode="2";
					}
				}
			} catch (Exception e) {
				marrcode="2";
				System.out.println("婚姻转化为编码失败");
			}
			entity.setCustMarr(marrcode);
			
			//学历c2（大学本科）
			String educode="1";
			try {
				String edu=record.getCustEndu();
				if(edu==null||edu.equals("")){
					educode="1";
				}else{
					if(edu.indexOf("硕士及以上")!=-1||edu.indexOf("硕士")!=-1){
						educode="1";
					}else if(edu.indexOf("本科")!=-1){
						educode="2";
					}else if(edu.indexOf("大中专")!=-1||edu.indexOf("大专")!=-1||edu.indexOf("中专")!=-1){
						educode="3";
					}else if(edu.indexOf("高中及以下")!=-1||edu.indexOf("高中")!=-1||edu.indexOf("初中")!=-1||edu.indexOf("小学")!=-1){
						educode="4";
					}else{
						educode="1";
					}
				}
			} catch (Exception e) {
				educode="1";
				System.out.println("教育程度转化为编码失败");
			}
			entity.setCustEndu(educode);
			
			
			//职位c3（一般员工）
			String titlcode="3";
			try {
				String titl=record.getCustTitl();
				if(titl==null||titl.equals("")){
					titlcode="3";
				}else{
					if(titl.indexOf("厅级")!=-1||titl.indexOf("局级")!=-1||titl.indexOf("高级")!=-1||titl.indexOf("高管")!=-1){
						titlcode="1";
					}else if(titl.indexOf("处级")!=-1||titl.indexOf("副处")!=-1||titl.indexOf("中级")!=-1||titl.indexOf("副科")!=-1){
						titlcode="2";
					}else if(titl.indexOf("普通企业")!=-1||titl.indexOf("普通")!=-1||titl.indexOf("一般")!=-1||titl.indexOf("技术")!=-1){
						titlcode="3";
					}else{
						titlcode="3";
					}
				}
			} catch (Exception e) {
				titlcode="3";
				System.out.println("职位转化为编码失败");
			}
			entity.setCustTitl(titlcode);
			
			
			//户籍c5（本地户籍）
			String registaddcode="2";
			try {
				String registadd=record.getCustRegistAdd();
				if(registadd==null||registadd.equals("")){
					registaddcode="2";
				}else{
					if(registadd.indexOf("本地户籍")!=-1||registadd.indexOf("本地")!=-1||registadd.indexOf("本地")!=-1){
						registaddcode="1";
					}else if(registadd.indexOf("外地户籍")!=-1||registadd.indexOf("外地")!=-1){
						registaddcode="2";
					}else{
						registaddcode="2";
					}
				}
			} catch (Exception e) {
				registaddcode="2";
				System.out.println("户籍转化为编码失败");
			}
			entity.setCustRegistAdd(registaddcode);
			
			
			//征信查询次数c6（7）
			String querycntcode="3";
			try {
				String querycntstr=record.getCustQueryCnt();
				if(querycntstr==null||querycntstr.equals("")){
					querycntcode="3";
				}else{
					int querycnt=Integer.parseInt(querycntstr);
					if(querycnt>=5){
						querycntcode="3";
					}else if(querycnt<5&&querycnt>=2){
						querycntcode="2";
					}else if(querycnt<2){
						querycntcode="1";
					}else{
						querycntcode="3";
					}
				}
			}catch (Exception e){
				querycntcode="3";
				System.out.println("征信查询次数转化为编码失败");
			}
			entity.setCustQueryCnt(querycntcode);
			
			
			//信用状况c7******************
			String custcreditcode="4";
			try {
				String custcreditstr=record.getCustCredit();
				if(custcreditstr==null||custcreditstr.equals("")){
					custcreditcode="4";
				}else{
					int custcredit=Integer.parseInt(custcreditstr);
					if(custcredit<1){
						custcreditcode="1";
					}else if(custcredit<=2&&custcredit>=1){
						custcreditcode="2";
					}else if(custcredit<=3&&custcredit>2){
						custcreditcode="3";
					}else if(custcredit>3&&custcredit<6){
						custcreditcode="4";
					}else{
						custcreditcode="4";
					}
				}
			} catch (Exception e) {
				custcreditcode="4";
				System.out.println("信用状况转化为编码失败");
			}
			entity.setCustCredit(custcreditcode);
			
			
			//当前有效贷记卡实用额度占授信总额c8********使用额度/授信总额
			String custvalidcreditcode="1";
			try {
				String custvalidcreditstr=record.getCustValidCredit();
				if(custvalidcreditstr==null||custvalidcreditstr.equals("")){
					custvalidcreditcode="1";
				}else{
					double custvalidcredit=new Double(custvalidcreditstr.substring(0,custvalidcreditstr.indexOf("%")))/100;
					if(custvalidcredit<0.3){
						custvalidcreditcode="1";
					}else if(custvalidcredit<0.5&&custvalidcredit>=0.3){
						custvalidcreditcode="2";
					}else if(custvalidcredit<0.7&&custvalidcredit>=0.5){
						custvalidcreditcode="3";
					}else if(custvalidcredit<0.9&&custvalidcredit>=0.7){
						custvalidcreditcode="4";
					}else if(custvalidcredit>=0.9){
						custvalidcreditcode="5";
					}else{
						custvalidcreditcode="1";
					}
				}
			} catch (Exception e) {
				custvalidcreditcode="0";
				System.out.println("授信总额转化为编码失败");
			}
			entity.setCustValidCredit(custvalidcreditcode);
		
			
			//未结清贷款余额********月供/工资
			String custlongbal="1";
			try {
				String custlongbalstr=record.getCustLongBal();
				if(custlongbalstr==null||custlongbalstr.equals("")){
					custlongbal="1";
				}else{
					double percent=new Double(custlongbalstr.substring(0,custlongbalstr.indexOf("%")))/100;
					if(percent<=0.3){
						custlongbal="1";
					}else if(percent>0.3&&percent<=0.5){
						custlongbal="2";
					}else if(percent>0.5&&percent<=0.8){
						custlongbal="3";
					}else if(percent>0.8){
						custlongbal="4";
					}else{
						custlongbal="1";
					}
				}
			} catch (Exception e) {
				custlongbal="1";
				System.out.println("贷款余额转化为编码失败");
			}
			entity.setCustLongBal(custlongbal);
			
			
			//数据日期（报告日期）
			String datadate=record.getInputDate();
			entity.setDataDate(datadate);
		}
	}
	
	//根据分值计算薪金贷额度
	private double getDaiKuanEDu(double score, double salary) {
		double edu=0.0;
		if(score>=6.5){
			System.out.print(salary+" * 18 = ");
			edu=salary*18;
		}else if(score>=6.0&&score<6.5){
			System.out.print(salary+" * 16 = ");
			edu=salary*16;
		}else if(score>=5.5&&score<6){
			System.out.print(salary+" * 14 = ");
			edu=salary*14;
		}else if(score>=5&&score<5.5){
			System.out.print(salary+" * 12 = ");
			edu=salary*12;
		}else if(score>=4.0&&score<5){
			System.out.print(salary+" * 10 = ");
			edu=salary*10;
		}else if(score>=3.0&&score<4){
			System.out.print(salary+" * 8 = ");
			edu=salary*8;
		}else if(score>=2.0&&score<3){
			System.out.print(salary+" * 6 = ");
			edu=salary*6;
		}else if(score>=1.6&&score<2){
			System.out.print(salary+" * 4 = ");
			edu=salary*4;
		}else if(score<1.6){
			System.out.print(salary+" * 2 = ");
			edu=salary*2;
		}
		return edu;
	}
	
	//征信接口
	@Override
	public ReturnData4Zx queryRhzx(HttpServletRequest request,RequestDataZx o) {
		ReturnData4Zx result=null;
		if(o.getCustno()==null||o.getCustidtno()==null||o.getProductcode()==null){
			result=new ReturnData4Zx(o.getCustno(), "0","报文缺失重要字段","0");
		}else{
			//获取客户名称
			String name=custDaiKuanDao.getCustName(o.getCustno(),o.getCustidtno());
			if(name!=null){
				try {
					if(custDaiKuanDao.isExistInBak(o.getCustidtno(),"1")){//检查是否在征信查询中
						result= new ReturnData4Zx(o.getCustno(),"0","征信查询中。。。","0");
					}else {
						boolean flag=postQueryDataToRenHang(o,name,rhzxurl);
						if(!flag){
							//备份征信请求
							result= new ReturnData4Zx(o.getCustno(), "1","征信查询请求已受理","0");
							custDaiKuanDao.insertBakCustNo(o.getCustidtno(),o.getCustno(),o.getProductcode(),"1");
							//放入数据库队列
							ZxcxData node=new ZxcxData(o.getCustno(), o.getCustidtno(),"1", o.getProductcode(), "", "");
							custDaiKuanDao.insertQueryZxcxData(node);
						}else{
							result= new ReturnData4Zx(o.getCustno(), "0","征信查询请求受理失败","0");
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					result= new ReturnData4Zx(o.getCustno(), "0","征信查询请求受理失败","0");
				}
			}else{
				result= new ReturnData4Zx(o.getCustno(), "0","找不到客户姓名","0");
			}
		}
		return result;
	}
	
	//获取信贷机构
	@Override
	public ReturnData4Org queryXdjg(RequestDataOrg o) {
		String org=custDaiKuanDao.getOrg(o.getCustidtno());
		if(org.equals("-1")){
			return new ReturnData4Org(o.getCustno(),"-1","暂时无法受理您的申请","");
		}else{
			return new ReturnData4Org(o.getCustno(),"1","查询成功",org);
		}
	}
	
	
	//RH调用crm后的处理
	@Override
	public ReturnData4Rh dealRHData(HttpServletRequest request,CustCreditRecord o) {
		ReturnData4Rh result=new ReturnData4Rh(o.getCustIdtNo(),"0");
		if(o.getCustIdtNo()!=null){
			ZxcxData bak=custDaiKuanDao.getBakBean(o.getCustIdtNo());//获取征信查询记录看当前请求是否已经处理
			if(bak!=null){
				try {
					setInvalidateInputdate(o);//设置征信失效日期加一个月
					o.setTimeOutBack("0");//设置征信报告返回未超期
					Serializable id=custDaiKuanDao.insertRecord(o);//存储RH数据
					if(id!=null){
						//通知手机端人行查询已经成功
						RequestDataPh returndata=new RequestDataPh(bak.getCustNo(),"1",bak.getProductCode(),"0");
						ReturnData4Ph returnFromPhone=this.postZxResultToPhone(returndata,sjyhurl);
						//更新征信请求，删除请求队列数据
						if(returnFromPhone!=null){
							int n=custDaiKuanDao.removeZxcxData(bak);
							System.out.println("删除队列数据结果:"+n);
							Serializable id2=custDaiKuanDao.updateBakCustNo(o.getCustIdtNo(),"2");
							System.out.println("更新征信请求结果:"+id2);
							result=new ReturnData4Rh(o.getCustIdtNo(),"1");
						}else{
							System.out.println("推送征信处理信息给手机银行失败");
						}
					}else{
						System.out.println("存储征信记录失败");
					}
				}catch(Exception e) {
					e.printStackTrace();
				}
			}else{
				System.out.println("重复接受征信报文！");
			}
		}
		return result;
	}
	
	//设置征信失效日期，记录
	private void setInvalidateInputdate(CustCreditRecord o){
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			String now =custDaiKuanDao.getNowTime("yyyy-MM-dd");//获取数据库当前时间
			if(o.getQueryDate().equals("")){
				o.setQueryDate(now);
				o.setInvalidDate(sdf.format(sdf.parse(now).getTime()+31*24*60*60*1000l));
				o.setInputDate(now);
			}else{
				o.setInvalidDate(sdf.format(sdf.parse(o.getQueryDate()).getTime()+31*24*60*60*1000l));
				o.setInputDate(now);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("设置失效日期，记录日期失败");
		}
	}
	
	//获取芝麻信用得分
	@Override
	public ReturnData4Zm queryZhimaScore(RequestDataZm o) {
		String data = null;
		try {
			data = objectMapper.writeValueAsString(o);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			System.out.println("数据对象转换为字符串失败");
		}

		if (data == null || data.equals("")) {
			System.out.println("发送的报文为空");
			return null;
		}

		String resultStr = null;
		try {
			resultStr = TuiSongUtils.tuiSong(data, zmxyurl);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			resultStr = null;
		} catch (IOException e) {
			e.printStackTrace();
			resultStr = null;
		}

		if (resultStr == null || resultStr.equals("")) {
			System.out.println("返回报文为空");
			return new ReturnData4Zm("-1", "", "查询芝麻积分失败", "0");
		} else {
			ReturnData4Zm resultObj = null;
			try {
				resultObj = objectMapper.readValue(resultStr, ReturnData4Zm.class);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("返回报文格式错误" + resultObj);
			}

			if (resultObj != null && resultObj.getSuccess().equals("1")) {
				System.out.println("推送报文数据成功");
				return resultObj;
			} else {
				System.out.println("推送报文数据失败");
				return new ReturnData4Zm("-1", "", "查询芝麻积分失败", "0");
			}
		}
	}
	
	//获取本行工资年龄
	@Override
	public String queryCustWorkAge(String custIdtNo) {
		String workage=custDaiKuanDao.queryCustWorkAge(custIdtNo);
		return workage;
	}
	
	//获取月平均工资
	@Override
	public String queryCustMonthBal(String custIdtNo) {
		String monthbal=custDaiKuanDao.queryCustMonthBal(custIdtNo);
		return monthbal;
	}
	
	
	//发送征信请求数据到人行
	public static boolean postQueryDataToRenHang(RequestDataZx o,String name,String rhzxUrl) {
		String xmlStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?><extraction><param><item><username>@name@</username><certype>@type@</certype><cercode>@id@</cercode><queryreason>02</queryreason><vertype>30</vertype><idauthflag>0</idauthflag></item></param></extraction>";
		xmlStr=xmlStr.replace("@name@", name.trim()).replace("@type@", "0").replace("@id@", o.getCustidtno());
		System.out.println(xmlStr);
		try {
			Object[] results=TuiSongUtils.xfire("wsPersonal",rhzxUrl, xmlStr);
			if(results.length>0){
				for(Object c :results){
					if(c.toString().equals("true")){
						System.out.println("renHangReturn:"+c);
						return true;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	
	//调用手机端通知结果
	private ReturnData4Ph postZxResultToPhone(RequestDataPh o,String url){
		String data = null;
		try {
			data = objectMapper.writeValueAsString(o);
			data=data.replace("main_NO", "MAIN_NO");
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			System.out.println("数据对象转换为字符串失败");
		}
		
		if(data==null||data.equals("")){
			System.out.println("发送的报文为空");
			return null;
		}
		
		String resultStr = null;
		try {
			resultStr = TuiSongUtils.tuiSong(data, url);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			resultStr = null;
		} catch (IOException e) {
			e.printStackTrace();
			resultStr = null;
		}
		
		if(resultStr==null||resultStr.equals("")){
			System.out.println("返回报文为空");
			return null;
		}else{
			ReturnData4Ph resultObj = null;

			try {
				resultObj = objectMapper.readValue(resultStr,ReturnData4Ph.class);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("返回报文格式错误"+resultObj);
			} 
			
			if(resultObj!=null&&resultObj.getStatus().equals("1")){
				System.out.println("推送报文数据成功");
				return resultObj;
			}else{
				System.out.println("推送报文数据失败");
				return null;
			}
		}
	}

}
